﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SBToolkit.Web
{
    /// <summary>
    /// Helper class for the <see cref="Page"/>.
    /// </summary>
    public static class PageHelper
    {
        /// <summary>
        /// Gets <see cref="Control"/> that performed post back.
        /// </summary>
        /// <param name="page">The <see cref="Page"/>.</param>
        /// <returns><see cref="Control"/> that performed post back.</returns>
        public static Control GetPostBackControl(this Page page)
        {
            Control control = null;
            string controlName = page.Request.Params["__EVENTTARGET"];

            if (!String.IsNullOrEmpty(controlName))
            {
                control = page.FindControl(controlName);
            }
            else
            {
                // if __EVENTTARGET is null, the control is a button type and we need to 
                // iterate over the form collection to find it
                foreach (string formControlName in page.Request.Form)
                {
                    Control formControl;
                    
                    // handle ImageButton controls ...
                    if (formControlName.EndsWith(".x") || formControlName.EndsWith(".y"))
                    {
                        controlName = formControlName.Substring(0, formControlName.Length - 2);
                        formControl = page.FindControl(controlName);
                    }
                    else
                    {
                        formControl = page.FindControl(formControlName);
                    }

                    if (formControl is Button || formControl is ImageButton)
                    {
                        control = formControl;
                        break;
                    }
                }
            }

            return control;
        }
    }
}
